package com.jn.glide.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.jn.glide.service.AvatarResponse;
import com.jn.glide.R;
import com.jn.glide.views.MainActivity;

import java.util.List;

public class AvatarsAdapter extends RecyclerView.Adapter<AvatarsAdapter.ViewHolder> {
    private List<AvatarResponse> avatars;
    private Context context;

    public AvatarsAdapter(List<AvatarResponse> avatars, Context context) {
        this.avatars = avatars;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_avatar, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        AvatarResponse avatar = avatars.get(position);
        holder.nameTextView.setText(avatar.getName());
        Glide.with(context).load(avatar.getIcon()).into(holder.iconImageView);

        holder.itemView.setOnClickListener(v -> {
            // 保存图片到相册
            ((MainActivity) context).saveImageToGallery(context, avatar.getIcon());
        });
    }

    @Override
    public int getItemCount() {
        return avatars.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView nameTextView;
        public ImageView iconImageView;

        public ViewHolder(View itemView) {
            super(itemView);
            nameTextView = itemView.findViewById(R.id.nameTextView);
            iconImageView = itemView.findViewById(R.id.iconImageView);
        }
    }
}